package com.tang.websocket.v1.session;

import com.tang.websocket.v1.message.PingMessage;
import com.tang.websocket.v1.message.PongMessage;
import com.tang.websocket.v1.message.TextMessage;
import com.tang.websocket.v1.message.WebSocketMessage;
import org.springframework.util.IdGenerator;
import org.springframework.util.JdkIdGenerator;

import java.io.IOException;

/**
 * @author Tang
 * @classname AbstractWebSocketSession
 * @description [  ]
 * @date 2022/11/25 17:34
 */
public abstract class AbstractWebSocketSession<T> implements NativeWebSocketSession {

    protected IdGenerator idGenerator = new JdkIdGenerator();

    private T nativeSession;

    public void initializeNativeSession(T session) {
        this.nativeSession = session;
    }

    @Override
    public void sendMessage(WebSocketMessage<?> message) throws IOException {
        if (message instanceof TextMessage) {
            handlerMsg((TextMessage) message);
            return;
        }
        if (message instanceof PingMessage) {
            handlerMsg((PingMessage) message);
            return;
        }
        if (message instanceof PongMessage) {
            handlerMsg((PongMessage) message);
            return;
        }
        handlerMsg(message);
    }

    protected abstract void handlerMsg(WebSocketMessage<?> message);

    protected abstract void handlerMsg(PongMessage message);

    protected abstract void handlerMsg(PingMessage message);

    protected abstract void handlerMsg(TextMessage message);

    @Override
    public Object getNativeSession() {
        return this.nativeSession;
    }

    @Override
    public <T> T getNativeSession(Class<T> tClass) {
        return (T)getNativeSession();
    }

}
